package com.shuidihuzhu.sdb.helper.log.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dongzhihua
 */
public class JsonUtil {
    private JsonUtil() {
    }

    public static <T> T fromJson(InputStream jsonInputStream, Class<T> clazz) {
        try {
            return new ObjectMapper().readValue(jsonInputStream, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将对象转换为json
     */
    public static String toJson(Object obj) {
        try {
            if (obj == null) {
                return null;
            }

            return new ObjectMapper().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            return obj.toString();
        }
    }

    /**
     * 获取对象json的描述，如果是集合，则最多展示3条记录
     * @param obj 对象
     * @return json或者描述
     */
    public static String toJsonDesc(Object obj) {
        if (obj == null) {
            return null;
        }
        String format = "size %d %s ...";

        if (obj.getClass().isArray()) {
            Object[] arr = (Object[]) obj;
            if (arr.length > 5) {
                final List<Object> list = Arrays.stream(arr).limit(3).collect(Collectors.toList());
                return String.format(format, arr.length, JsonUtil.toJson(list));
            }
        }

        if (obj instanceof Collection) {
            Collection<Object> collection = (Collection<Object>) obj;
            if (collection.size() > 5) {
                final List<Object> list = collection.stream().limit(3).collect(Collectors.toList());
                return String.format(format, collection.size(), JsonUtil.toJson(list));
            }
        }

        if (obj instanceof Map) {
            Map<Object, Object> map = (Map<Object, Object>) obj;
            if (map.size() > 5) {
                final List<Map.Entry<Object, Object>> list = map.entrySet().stream().limit(3).collect(Collectors.toList());
                return String.format(format, map.size(), JsonUtil.toJson(list));
            }
        }

        return JsonUtil.toJson(obj);
    }
}
